<?php

namespace app\zyhsapi\model;

use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsConsultAstrData extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_consult_astr_data';

    protected $cacheModel = 'astr_admin.consult_account_data_analysis';

    /**
     * 初始化 咨询会话ID
     * @param array $data
     * @return int
     */
    public function SaveData(array $data): int
    {
        try
        {
            $chatId = $this->insertGetId($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('data_id', $data['astr_id'] . ':' . $data['time'])->rmCache('data_id');
            return (int)$chatId;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    public function updateData($id, $data)
    {
        try
        {
            $data['update_time'] = time();
            $this->where(['id' => $id])->update($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        // 获取未删除 的数据
        $where = ['id' => ['in', $ids]];

        $field = 'id,astr_id,time,reply_num,min5_reply_num,level5_comment,level1_comment,service_duration,service_num,recommend_num,create_time,update_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'astr_id', 'time', 'reply_num', 'min5_reply_num', 'level5_comment', 'level1_comment', 'service_duration', 'service_num', 'recommend_num', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * 更新信息
     * @param $astrId
     * @param $time
     * @param $data
     * @return bool
     */
    public function analysisDataUpdate($astrId, $time, $data)
    {
        try
        {
            $chatId = $this->getDataId($astrId, $time);
            $info = $chatId > 0 ? $this->getInfoById($chatId) : null;
            if ($info)
            {
                $this->updateData($info['id'], $data);
            } else
            {   // 初始化
                $insertData = [
                    'astr_id' => $astrId,
                    'time' => $time,
                    'create_time' => time(),
                ];

                if (isset($data['reply_num']))
                {
                    $insertData['reply_num'] = 1;
                }
                if (isset($data['min5_reply_num']))
                {
                    $insertData['min5_reply_num'] = 1;
                }
                if (isset($data['level5_comment']))
                {
                    $insertData['level5_comment'] = 1;
                }
                if (isset($data['level1_comment']))
                {
                    $insertData['level1_comment'] = 1;
                }
                if (isset($data['service_duration']))
                {
                    $insertData['service_duration'] = $data['service_duration'];
                }
                if (isset($data['service_num']))
                {
                    $insertData['service_num'] = 1;
                }
                if (isset($data['recommend_num']))
                {
                    $insertData['recommend_num'] = 1;
                }

                $this->SaveData($insertData);
            }

            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取指定  咨询师的会话ID chatId
     * @param int $astrId
     * @param int $time
     * @return int
     * @throws \Exception
     */
    public function getDataId(int $astrId, int $time): int
    {
        $data = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('data_id', $astrId . ':' . $time)
            ->getDataAndSet(function () use ($astrId, $time)
            {
                try
                {
                    $id = $this->where(['astr_id' => $astrId])->where('time', $time)->order('id desc')->value('id');
                    if ($id)
                    {
                        $data = ['id' => $id];
                    } else
                    {
                        $data = ['id' => 0];
                    }
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = ['id' => 0];
                }
                return $data;
            }, [], 'data_id');

        return (int)($data['id'] ?? 0);
    }

    /**
     * 获取排行信息
     * @param int $type 1=>咨询榜 2=>热度榜
     * @return array
     * @throws \Exception
     */
    public function getRankingList(int $type)
    {
        if ($type === 1)
        {
            $cacheKeyId = '1:' . date('mdH');
        } else
        {
            $cacheKeyId = '2:' . mb_substr(date('mdHi'), 0, 7);
        }
        $pageData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('ranking', $cacheKeyId)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($type, $cacheKeyId)
            {
                try
                {   //                  咨询榜 3天以前的时间   热度榜 8小时以前的时间
                    $time = $type === 1 ? time() - 259200 : time() - 28800;
                    $timeDate = (int)date('YmdH', $time);
                    $data = $this->where(['time' => ['>=', $timeDate]])->group('astr_id')->column('sum(reply_num) reply_nums,sum(min5_reply_num) min5_reply_nums,sum(level5_comment) level5_comments,sum(level1_comment) level1_comments,sum(service_duration) service_durations,sum(service_num) service_nums,sum(recommend_num) recommend_nums', 'astr_id');
                    // 获取所有的咨询师IDS
                    // reply_nums           回复总数
                    // min5_reply_nums      5分钟内回复总数
                    // level5_comments      好评总数
                    // level1_comments      差评总数
                    // service_durations    服务时长
                    // service_nums         服务次数
                    // recommend_nums       推荐次数
                    $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
                    $consultAstrPageData = $zlcr3ConsultAccountModel->getChatConsultIds(0, -1);
                    $consultAstrIds = $consultAstrPageData['data'];
                    $dataList = [];
                    foreach ($consultAstrIds as $astrId)
                    {
                        $consultAstrInfo = $zlcr3ConsultAccountModel->getInfoById($astrId);
                        if ($consultAstrInfo['consult_status'] != 1)
                        {   // 禁止 连麦 不上排行榜
                            continue;
                        }
                        if (isset($data[$astrId]))
                        {
                            if ($type === 1)
                            {   // 咨询榜
                                // 好评分值 + 服务推荐率分值 - 差评率分值 = 咨询专业值
                                // 好评率分值 = （好评量 / 咨询量）* 100
                                // 推荐率分值 = （推荐量 / 咨询量）* 1000
                                // 差评率分值 = （差评量 / 咨询量）* 50
                                if ($data[$astrId]['service_nums'])
                                {
                                    $dataList[$astrId] = ($data[$astrId]['level5_comments'] / $data[$astrId]['service_nums']) * 100 + ($data[$astrId]['recommend_nums'] / $data[$astrId]['service_nums']) * 1000 - ($data[$astrId]['level1_comments'] / $data[$astrId]['service_nums']) * 50 + ($consultAstrInfo['extend']['ability_score'] ?? 0);
                                } else
                                {   // 未产生服务 不纳入排名
                                    if (isset($consultAstrInfo['extend']['ability_score']) && $consultAstrInfo['extend']['ability_score'] > 0)
                                    {
                                        $dataList[$astrId] = (int)$consultAstrInfo['extend']['ability_score'];
                                    }
                                    continue;
//                                    $dataList[$astrId] = 0;
                                }
                            } else
                            {   // 热度榜
                                // 回复咨询量分值 + 回复响应速度分值 = 热度值
                                // 回复咨询量分值   = 回复总量 * 100
                                // 回复响应速度分值 = 5分钟回复量 * 300
                                $dataList[$astrId] = ($data[$astrId]['reply_nums']) * 100 + ($data[$astrId]['min5_reply_nums']) * 300 + ($consultAstrInfo['extend']['hot_score'] ?? 0);
                            }
                        } else
                        {
                            if ($type === 1)
                            {   // 咨询榜单 未产生服务 不纳入排名
                                if (isset($consultAstrInfo['extend']['ability_score']) && $consultAstrInfo['extend']['ability_score'] > 0)
                                {
                                    $dataList[$astrId] = (int)$consultAstrInfo['extend']['ability_score'];
                                }
                                continue;
                            } else
                            {
                                $dataList[$astrId] = (int)($consultAstrInfo['extend']['hot_score'] ?? 0);
                            }
                        }

                        $dataList[$astrId] = sprintf('%.6f', $dataList[$astrId] + $astrId / 1000000);
                    }
                    arsort($dataList);
                    $resData = [];
                    foreach ($dataList as $astrId => $score)
                    {
                        $resData[$astrId] = ['score' => $score];
                    }

                    CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('ranking', $cacheKeyId)->setPage(-1)->setSort('desc')->setListCacheTime($type === 1 ? 3610 : 610);
                    return $resData;
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    return [];
                }
            }, 'score', 0, 'ranking');

        return $pageData['data'];
    }
}